package com.moxiu.browser.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


import android.util.Log;

public class BrowserAdblockImpl implements BrowserAdblock {
	
	private static BrowserAdblockImpl browserAdblockImpl = null;
	
	private Boolean adBlockSwitch = true;   //广告屏蔽开关
	
	private BrowserAdblockImpl() {};
	
	public static synchronized BrowserAdblockImpl getInstance(){
		if (browserAdblockImpl == null) {
			browserAdblockImpl = new BrowserAdblockImpl();
		}
		return browserAdblockImpl;
	}

	@Override
	public void showSource(String html) {
		Log.i(TAG, html);
	}

	@Override
	public void adblockControl(Boolean isOpen) {
		adBlockSwitch = isOpen;
	}

	@Override
	public boolean adUrlMatching(String url) {
		if (this.adBlockSwitch) {
//			Pattern pBaidu = Pattern.compile(ADBLOCK_BAIDU_REGULAR);
//			Pattern p360dc = Pattern.compile(ADBLOCK_360DC_REGULAR);
//			Matcher mBaidu = pBaidu.matcher(url);
//			Matcher m360dc = p360dc.matcher(url);
//			Log.i("ad_block", "matching : " + mBaidu.find() + " 360 : " + m360dc.find());
			Log.i("ad_block", url);
//			Log.i("ad_block", "############################## " + adBaiduMatching(url));
			if (adBaiduMatching(url) || ad360dcMatching(url)) {
				return true;
			}
		}
		return false;
	}
	
	boolean adBaiduMatching(String url){
		for (String regular : ADBLOCK_BAIDU_REGULAR) {
			Pattern pattern = Pattern.compile(regular);
			Matcher matcher = pattern.matcher(url);
//			Log.i("ad_block", "【url】 : " + url + " 【regular】 : " + ADBLOCK_BAIDU_REGULAR[0] + "【final】" + matcher.find());
			if (matcher.find()) {
				return true;
			}
		}
//		
		return false;
//			return matcher.find();	
	}
	
	boolean ad360dcMatching(String url){
		Pattern pattern = Pattern.compile(ADBLOCK_360DC_REGULAR);
		Matcher matcher = pattern.matcher(url);
//		Log.i("ad_block", "360 : " + matcher.find());
//		if (matcher.find()) {
//			return true;
//		}else {
//			return false;
//		}
		return matcher.find();
	}

	@Override
	public String[] adBlockByJs() {
		if (adBlockSwitch) {
			return ADBLOCK_JS;
		}else {
			return null;
		}
		
	}
}
